<?php

namespace app\api\controller;

use app\api\Base;
use app\common\model\Monitor;
use app\common\model\User;
use app\common\model\UserCompany;
use com\gdl\agk\dataobject\basic\BasicDTO;
use com\gdl\agk\dataobject\basic\FaceType;
use think\Config;
use think\Exception;
use app\common\model\Examsession;
use com\gdl\agk\interfaces\BasicServiceClient;
use think\Db;
/**
 * Created by PhpStorm.
 * User: 监控接口
 * Date: 2017/6/9 0009
 * Time: 下午 3:59
 */
class MonitorServiceApi extends Base  {
    /**
     * 人脸识别
     * @return string
     */
    public function faceRecognition()
    {
        $identity_id = (int) $this->request->param('identity_id'); //身份id
        $basicid = (int) $this->request->param('basicid');
        $type = (int) $this->request->param('type');
        $username = $this->request->param('username');
        if (!$_FILES['file']['name']) {
            $data = [['id' => 'n']];
            return json_encode($data);
        }
//        $result = \Qiniu::instance()->upload(); //七牛上传
//        $address = $result[0]['key'];
//        $address = Config::get('qiniu.QINIU_DOMAIN') . $address;
       

        //变更人脸识别接口根据人员切换 2018-03-08 by yanghao     
        $faceSdk = strtolower('youtu');
        $faceType = 2;
        $souce_image = file_get_contents($_FILES['file']['tmp_name']);
        if ($faceType == 2) {
            $faceImgA = base64_encode(file_get_contents($_FILES['file']['tmp_name']));
        } else {
            $faceImgA = createLocalFile($address, '../upload/facetemp/', in_array($faceSdk, array('youtu')));
        }

        //获取用户的留底照片
        $photo_collect = Db::name('user')->where(['id' => $identity_id])->field("userId,photoCollect,vface")->find();
        if ($photo_collect['vface'] == 2 && !empty($photo_collect['photoCollect'])) {
            if ($faceType == 2) {
                $faceImgB = base64_encode(file_get_contents($photo_collect['photoCollect']));
//                $faceImgB = $photo_collect['photoCollect']; //如果优图才启用 URL
            } else {
                $faceImgB = createLocalFile($photo_collect['photoCollect'], '../upload/facetemp/', in_array($faceSdk, array('youtu'))); //获取图片内容
            }
        }

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk'));
            $userService = new BasicServiceClient(NULL);

            $MonitorModel = new Monitor();
            $ExamsessionModel = new Examsession();
            \ApiClient::build($userService);
            $BasicDTO = new BasicDTO();
            $BasicDTO->name = $faceImgA;
            $BasicDTO->field = $faceImgB;
            $BasicDTO->type = $faceType;
            $faceMessage = Config::get('message.face');
            $similarity = 0;
            $judgeResult = -1;
            //比对的两张照片同时不为空，才可以调用比对接口
            if (!empty($faceImgA) && !empty($faceImgB)) {
                $result = $userService->identify($BasicDTO);
                $similarity = $result->data[0]['similarity'];
                $judgeResult = $faceSdk == 'facevisa' ? $result->data[0]['result'] : $result->data[0]['errorcode'];
            } else {
                $remark = 'no source img';
                $similarity = 0;
            }

            $monitorInfo = [
                'identity_id' => $identity_id,
                'truename' => $username,
                'current_img' => $address,
                'source_img' => $photo_collect['photo_collect'], //留底照片
                'similarity' => $similarity,
                'judge_result' => $judgeResult,
                'reason' => $faceMessage[FaceType::message2],
                'face_sdk' => $faceSdk,
                'remark' => $remark,
                'type' => $type,
                'parm' => $basicid,
                'create_time' => time(),
            ];
            
            if ($similarity >= FaceType::PASS || $judgeResult >= 2) {
                $monitorInfo['suspicion'] = 1;
                $ExamsessionModel->modifyExamSession(['suspicion' => 0], session_id());
                $id = $MonitorModel->insertMonitor($monitorInfo);

                $msg = [
                    'id' => $id,
                    'image' => base64_encode($souce_image)
                ];
                $host_config = Config::get('rabbitmq.config');
                $upload = Config::get('rabbitmq.upload');
                $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
                $rabbitMq->send($msg);

                return json_encode(['statusCode' => 200, 'massage' => $faceMessage[FaceType::message1]]);
            } else {
                $monitorInfo['suspicion'] = 0;
                $ExamsessionModel->modifyExamSession(['suspicion' => 1], session_id());
                $id = $MonitorModel->insertMonitor($monitorInfo);

                $msg = [
                    'id' => $id,
                    'image' => base64_encode($souce_image)
                ];
                $host_config = Config::get('rabbitmq.config');
                $upload = Config::get('rabbitmq.upload');
                $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
                $rabbitMq->send($msg);

                return json_encode(['statusCode' => 300, 'massage' => $faceMessage[FaceType::message1]]);
            }
        } catch (Exception $ex) {
            \SLogger::getLogger('job_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
    }

}
